import React, { memo, useEffect, useRef, useState } from "react"
import { LeftOutlined, RightOutlined } from '@ant-design/icons'

import { ViewWrapper } from "./style"

const ScrollView = memo((props) => {
  const [ showRightBtn, setShowRightBtn ] = useState(false)
  const [ showLeftBtn, setShowLeftBtn ] = useState(false)

  // 偏移几个子元素，posIndex为最左侧的元素
  const [ posIndex, setPosIndex] = useState(0)

  // 获取可以滚动的大小
  const scrollContentRef = useRef()
  // 已滚动的距离
  const scrollDistanceRef = useRef()

  useEffect(() => {
    // 滚动宽度
    const scrolltWidth = scrollContentRef.current.scrollWidth
    // 显示宽度
    const clientWidth = scrollContentRef.current.clientWidth
    // 可滚动距离
    const scrollDistance = scrolltWidth - clientWidth
    scrollDistanceRef.current = scrollDistance
    // 是否显示右侧按钮
    setShowRightBtn(scrollDistance > 0)
  }, [props.children])

  // 翻页滚动按钮点击
  const scrollBtnClick = (val) => {
    // 记录新索引，newIndex为新的最左侧元素
    const newIndex = posIndex + val
    setPosIndex(newIndex)

    // 获取新元素距离左侧距离,偏移相应的距离
    const newScrollDistance = scrollContentRef.current.children[newIndex].offsetLeft
    scrollContentRef.current.style.transform = `translate(-${newScrollDistance}px)`

    if(val>0) {
      // 点击右侧按钮,显示左侧按钮
      setShowLeftBtn(true)
      // 判断是否继续显示右侧按钮，可滚动距离大于已滚动距离时显示
      setShowRightBtn(scrollDistanceRef.current - newScrollDistance > 0)
    } else {
      // 点击左侧按钮,显示右侧按钮
      setShowRightBtn(true)
      // 是否显示左侧按钮，滚动距离大于0时显示
      setShowLeftBtn(newScrollDistance > 0)
    }
  }

  return (
    <ViewWrapper>
      {
        showLeftBtn && (
        <div className="button button-left" onClick={() => scrollBtnClick(-1)}>
          <LeftOutlined /> 
        </div>
        )
      }
      <div className="content-container">
        <div className="scroll-content" ref={scrollContentRef}>
          { props.children }
        </div>
      </div>
      {
        showRightBtn && (
        <div className="button button-right" onClick={() => scrollBtnClick(1)}>
          <RightOutlined />
        </div>
        )
      }
    </ViewWrapper>
  )
});

ScrollView.propTypes = {}

export default ScrollView
